package com.fjrcloud.service;

import com.fjrcloud.dao.HouseholdArchivesDao;
import com.fjrcloud.dao.HouseholdMasterDao;
import com.fjrcloud.dao.HouseholdUploadCollectionDao;
import com.fjrcloud.dao.HouseholdUploadFileDao;
import com.fjrcloud.entity.*;
import com.fjrcloud.exception.BusinessException;
import com.fjrcloud.utils.PageUtils;
import com.fjrcloud.utils.SerialNumberUtils;
import com.fjrcloud.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by shengjian.lin on 17-1-7.
 */
@Service
public class HouseholdService {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HouseholdMasterDao masterDao;
    @Autowired
    private HouseholdArchivesDao archivesDao;
    @Autowired
    private HouseholdUploadCollectionDao collectionDao;
    @Autowired
    private HouseholdUploadFileDao fileDao;
    @Autowired
    private ProjectService projectService;

    public Page<HouseholdMaster> masters(Integer pageNum, Integer pageSize) throws BusinessException {

        pageNum = PageUtils.checkPageNum(pageNum);
        pageSize = PageUtils.checkPageSize(pageSize);
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);

        return masterDao.findByGroupInAndValidOrderByCreateTimeDesc(getProjectGroup(),true,pageRequest);
    }

    private List<ProjectGroup> getProjectGroup() throws BusinessException {

        List<ProjectGroup> groups = new ArrayList<ProjectGroup>();

        UserType type = (UserType) request.getSession().getAttribute("user-type");
        if (UserType.root.equals(type)) {
            Page<ProjectGroup> page = projectService.list(null,null);
            groups = page.getContent();
        } else {
            groups.add(getUser4ProjectGroup());
        }

        return groups;
    }
    private ProjectGroup getUser4ProjectGroup() throws BusinessException {
        User user = (User) request.getSession().getAttribute("user");
        if (user.getGroup() == null)
            throw new BusinessException("当前登录用户没有项目组,无法进行该操作");

        return user.getGroup();
    }

    public HouseholdMaster getMaster(Integer id) throws BusinessException {
        return masterDao.findByGroupInAndIdAndValid(getProjectGroup(),id,true);
    }
    public HouseholdMaster delMaster(Integer id) throws BusinessException {
        if (id == null)
            throw new BusinessException("删除对象无效");
        HouseholdMaster master = masterDao.findByGroupInAndIdAndValid(getProjectGroup(),id,true);
        if (master == null)
            throw new BusinessException("删除对象无效");

        master.setValid(false);
        return masterDao.save(master);
    }
    public HouseholdMaster saveMaster(HouseholdMaster master) throws BusinessException {

        if (master.getId() == null){
            HouseholdMaster master1 = masterDao.findByCollectAddressAndValid(master.getCollectAddress(),true);
            if (master1 != null)
                throw new BusinessException("原房屋坐落 "+master.getCollectAddress() +" 已经存在数据库中");
            try {
                master.setCode(SerialNumberUtils.get());
            } catch (ParseException e) {
                throw new BusinessException("生成流水号错误");
            }
            master.setGroup(getUser4ProjectGroup());
        }else{

            HouseholdMaster old = masterDao.findOne(master.getId());
            if (old == null)
                throw new BusinessException("修改对象不存在");

            master.setCode(old.getCode());
            master.setDisposable(old.getDisposable());
            master.setBuyArea(old.getBuyArea());
            master.setErrorArea(old.getErrorArea());

            master.setGroup(old.getGroup());
        }

        master.setCreateTime(System.currentTimeMillis());
        return masterDao.save(master);
    }

//    public HouseholdArchives saveArchive(Integer masterId,Integer templateId,String data) throws BusinessException {
//
//        System.out.println(masterId);
//        HouseholdMaster master = masterDao.findOne(masterId);
//        if (master == null || !master.getValid())
//            throw new BusinessException("被征收人 不存在");
//
//        TemplateCurrent template = templateService.get(templateId);
//        if (template == null || !template.getValid())
//            throw new BusinessException("电子档案类型 不存在");
//
//        HouseholdArchives archive = new HouseholdArchives();
//        archive.setCode(DateUtils.getCurrentDate());
//        archive.setMaster(master);
//        archive.setTemplate(template.getWarehouse());
//        archive.setData(data);
//        archive.setCreateTime(System.currentTimeMillis());
//
//        return archivesDao.save(archive);
//    }
    public HouseholdArchives getArchive(Integer id){
        return archivesDao.findOne(id);
    }
//    public HouseholdArchives archiveRefresh(Integer id) throws BusinessException {
//        HouseholdArchives archives = archivesDao.findOne(id);
//        if(archives == null)
//            throw new BusinessException("要刷新的文档无效");
//
//        TemplateWarehouse warehouse = archives.getTemplate();
//        TemplateCurrent current = templateService.get(warehouse.getName());
//
//        archives.setTemplate(current.getWarehouse());
//
//        return archivesDao.save(archives);
//    }
//    public List print(Integer[] masterIds, Integer templateId,Boolean isCurrent,Integer pageNum, Integer pageSize) throws BusinessException {
//
//        if (templateId == null)
//            throw new BusinessException("没有选择要打印的文档");
//        if (masterIds == null || masterIds.length == 0)
//            throw new BusinessException("没有选择要打印的对象");
//
//        TemplateWarehouse template;
//        if(isCurrent != null && isCurrent == true){
//            TemplateCurrent current = templateService.get(templateId);
//            if (current == null)
//                throw new BusinessException("选择要打印的文档无效");
//            else
//                template = current.getWarehouse();
//        }else{
//            template = templateService.getWarehouse(templateId);
//        }
//
//        if (template == null)
//            throw new BusinessException("选择要打印的文档无效");
//
//        pageNum = PageUtils.checkPageNum(pageNum);
//        pageSize = PageUtils.checkPageSize(pageSize);
//        PageRequest pageRequest = new PageRequest(pageNum, pageSize);
//
//        Page<HouseholdMaster> masters = masterDao.findByIdInAndValidOrderByCreateTimeDesc(masterIds,true,pageRequest);
//
//
//        Page<HouseholdArchives> archives = archivesDao.findByMasterInAndTemplateAndValidOrderByCreateTimeDesc(masters.getContent(),template,true,pageRequest);
//
//        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
//
//        for (HouseholdArchives archive :archives.getContent()) {
//
//            Map<String,Object> map = new HashMap<String, Object>();
//            map.put("master",archive.getMaster());
//            map.put("code",archive.getCode());
//            map.put("data",archive.getData());
//            map.put("template",archive.getTemplate());
//
//            list.add(map);
//        }
//
//        return list;
//    }
    public HouseholdUploadCollection saveCollection(Integer id,String name) throws BusinessException {

        HouseholdUploadCollection collection = collectionDao.findByNameAndValid(name,true);

        if(collection != null)
            throw new BusinessException("档案名次已经存在");

        HouseholdMaster master = masterDao.findOne(id);
        if (master == null || !master.getValid())
            throw new BusinessException("没有主体数据");

        collection = new HouseholdUploadCollection();
        collection.setName(name);
        collection.setMaster(master);
        collection.setCreateTime(System.currentTimeMillis());

        return collectionDao.save(collection);
    }

    public HouseholdUploadFile upload(Integer id,MultipartFile mfile,String name) throws BusinessException {

        HouseholdUploadCollection collection = collectionDao.findOne(id);

        if (collection == null || !collection.getValid())
            throw new BusinessException("档案名次已经存在");

        Date currentTime = new Date();
        SimpleDateFormat path = new SimpleDateFormat("/yyyy/MM/dd");
        SimpleDateFormat fileName = new SimpleDateFormat("HHmmssSSS");

        String filePath = UploadUtils.upload(mfile,path.format(currentTime),fileName.format(currentTime));

        HouseholdUploadFile file = new HouseholdUploadFile();
        file.setName(name);
        file.setPath(filePath);

        String oriFileName = mfile.getOriginalFilename();
        file.setSuffix(oriFileName.substring(oriFileName.lastIndexOf(".")+1));

        file.setCollection(collection);
        file.setCreateTime(System.currentTimeMillis());

        return fileDao.save(file);
    }
    public Set<HouseholdUploadFile> getFiles(Integer id) throws BusinessException {

        HouseholdUploadCollection collection = collectionDao.findOne(id);
        if (collection == null || !collection.getValid())
            throw new BusinessException("档案集合不存在");

        return collection.getFiles();
    }

//    public HouseholdMaster find(Integer id){
//        return masterDao.findOne(id);
//    }

    public List<HouseholdMaster> findByIdNo(String idNo) {
        return masterDao.findByIdNoAndValid(idNo,true);
    }

    public Page<HouseholdMaster> find(HouseholdMaster master,Integer pageNum, Integer pageSize) throws BusinessException {

        pageNum = PageUtils.checkPageNum(pageNum);
        pageSize = PageUtils.checkPageSize(pageSize);
        PageRequest pageRequest = new PageRequest(pageNum, pageSize);

        return masterDao.findByGroupInAndValidAndCodeLikeAndNameLikeAndCollectAddressLikeAndIdNoLike(getProjectGroup(),
                true,
                "%"+master.getCode()+"%",
                "%"+master.getName()+"%",
                "%"+master.getCollectAddress()+"%",
                "%"+master.getIdNo()+"%",
                pageRequest
                );

    }
    public HouseholdMaster setDisposable(Integer masterId,Double price) throws BusinessException {

        if(masterId == null)
            throw new BusinessException("主体不能为空");
        HouseholdMaster master = masterDao.findOne(masterId);
        if (master == null)
            throw new BusinessException("主体错误");

        master.setDisposable(price);

        return masterDao.save(master);
    }
    public HouseholdMaster setBuyArea(Integer masterId,Double area) throws BusinessException {

        if(masterId == null)
            throw new BusinessException("主体不能为空");
        HouseholdMaster master = masterDao.findOne(masterId);
        if (master == null)
            throw new BusinessException("主体错误");

        master.setBuyArea(area);

        return masterDao.save(master);
    }
    public HouseholdMaster setErrorArea(Integer masterId,Double area) throws BusinessException {

        if(masterId == null)
            throw new BusinessException("主体不能为空");
        HouseholdMaster master = masterDao.findOne(masterId);
        if (master == null)
            throw new BusinessException("主体错误");

        master.setErrorArea(area);

        return masterDao.save(master);
    }

}
